﻿//作者: 小k
var defaults = {
    datagrid: {
        width: 700,
        pagination: true,
        rownumbers: true,
        columns: [],
        queryParams:{}
    },
    tag: {
        columns: [],
        queryurl: '' //查询url
    }
};
 
//定义对象
var picker = {
    setting: {
        parent: '',
        value: 'pickervalue',
        text: "pickertext",
        content: "box",
        pickerbox: '',
        count: "count",
        ismultiple: jQuery.query.get('ismultiple') == 'true' ? true : false
    },
    //创建
    build: function (options) {

        if (jQuery.query.get('pickerbox') != "") {
            picker.setting.pickerbox = jQuery.query.get('pickerbox');
            picker.setting.parent = jQuery.query.get("parentid");

            if (parent.$("#temppickervalue").val() == "") {
                jQuery("#" + picker.setting.value).val('');
                jQuery(picker.setting.content).html('');
            }
            else {
                jQuery("#" + picker.setting.value).val(parent.$("#temppickervalue").val() + ",");
                if (jQuery.query.get('tagname') == "input") {
                    var html = '';
                    var pickertext = (parent.$("#" + picker.setting.pickerbox).val() + ',').toString().split(',');
                    var pickervalue = jQuery("#" + picker.setting.value).val().split(",");
                    var text = '';
                    for (var i = 0; i < pickertext.length - 1; i++) {
                        text += pickertext[i] + ',';
                        html += "<option value='" + pickervalue[i] + "'>" + pickertext[i] + "</option>";
                    }
                    jQuery("#" + picker.setting.content).html(html);
                    jQuery("#" + picker.setting.text).val(text);
                }
                else {
                    jQuery("#" + picker.setting.content).html(parent.$("#temppickertext").val() + ',');
                }
            }
        }
        picker.grid.fieldtext = jQuery.query.get('fieldtext');
        picker.grid.fieldvalue = jQuery.query.get('fieldvalue');
        //合并到defaults
        var opts = $.extend(defaults, defaults, options);
 
        picker.grid.datagrid(opts);
        picker.tag.datatag(opts);
        picker.bindEvent(opts);
        loadTree();
    },
    //关闭
    close: function () {
        picker.setValue();
        $("#AsyncBox_close").click();
        //$.close("AsyncBox");
    },
    //事件绑定
    bindEvent: function () {
        (function () {
            jQuery('html').keydown(function (e) {
                if (e.keyCode == 13) {
                    //if (jQuery.trim(jQuery("#searchText").val()) == "") return;
                    picker.tag.query(defaults);
                }
            });

            jQuery("#finish").bind("click", function () {
                picker.close();
            });

            jQuery("#deletebtn").bind("click", function () {
                picker.box.button.del();
            });

            jQuery("#clearbtn").bind("click", function () {
                picker.box.button.clear();
            });

            jQuery("#searchbtn").bind("click", function () {
                picker.tag.query(defaults);
            });

            jQuery("#cancel").bind("click", function () {
                $("#AsyncBox_close").click();
            });
        })();
    },
    //设置值到pickerbox
    setValue: function () {
        var id = picker.setting.pickerbox;
        if (id != "" && id != null)
            if (picker.setting.parent == true) {
                setValueToPickerBox(top);
            }
            else {
                setValueToPickerBox($.framer(picker.setting.parent));
            }
    },
    //更新值、文本
    update: function (id, value) {
        var re = new RegExp(value + ",", "g");
        var str = jQuery("#" + id).val();
        var newstart = str.replace(re, "");
        jQuery("#" + id).val(newstart);
    }
};

//picker.tag继承
picker.tag = {
    datatag: function (opts) {
        var len = opts.tag.columns.length;
        if (opts.tag.columns[0] == 0) {
            $("#panel-title").css("height", "20px");
            return;
        }
        var html = '';
        var navindex = jQuery.query.get('navindex');
        for (var i = 0; i < len; i++) {
            for (var j = 0; j < opts.tag.columns[i].length; j++) {
                html += "<a id='tag" + j + "'class='navindex' href='javascript:void(0)' style='display:none'>" + opts.tag.columns[i][j].name + "</a>  ";
            }
        }
        if (html != '')
            $("#panel-title").html(html);
        //等于false 默认全部显示
        if (navindex == "false") {
            $("a[class='navindex']").show();
        }
        //否则检测对应索引
        else {
            if (navindex.substr(navindex.length - 1, 1) == ',') {
                navindex = navindex;
            }
            else
                navindex = navindex + ',';

            for (i = 0; i < navindex.split(',').length; i++) {
                $("a[id='tag" + navindex[i] + "']").show();
            }
        }
        picker.tag.bindEvent(opts);
    },
    query: function (opts) {
        jQuery('#pickergrid').datagrid({
            url: opts.tag.queryurl
        });
    },
    bindEvent: function (opts) {
        $("#panel-title>a").each(function (i) {
            jQuery(this).unbind('click').bind('click', function () {
                jQuery('#pickergrid').datagrid({
                    url: opts.tag.columns[0][i].url,
                    columns: opts.datagrid.columns
                                });
            });
        });
    }
};

//picker.box继承
picker.box = {
    getValueArray:function () {
        return jQuery("#" + picker.setting.value).val().split(",");
    },
    //获取box的值
    getValue: function () {
        return jQuery("#" + picker.setting.value).val();
    },
    //获取box的文本以,号分割
    getText: function () {
        var str = '';
        var pickertext = jQuery("#" + picker.setting.text).val().split(',');
        if (pickertext.length == 1)
            return pickertext;
        for (var i = 0; i < pickertext.length - 1; i++) {
            str += pickertext[i] + ",";
        }
        return str.substr(0, str.length - 1);
    },
    //获取box的内容
    getContent: function () {
        return jQuery("#" + picker.setting.content).html();
    },
    //获取box的数量
    getCount: function () {
        return jQuery("#" + picker.setting.count).text();
    },
    //设置box数量
    setCount: function () {
        jQuery("#" + picker.setting.count).text(jQuery("#" + picker.setting.value).val().split(",").length - 1);
    },
    //删除
    del: function (rowindex, rowdata) {
        var arrlist = jQuery("#" + picker.setting.value).val().split(",");
        for (var i = 0; i < arrlist.length; i++) {
            if (arrlist[i] == rowdata[picker.grid.fieldvalue]) {
                picker.update(picker.setting.value, arrlist[i]);
                picker.update("pickertext", rowdata[picker.grid.fieldtext]);
                jQuery("#" + picker.setting.content + " option[value='" + rowdata[picker.grid.fieldvalue] + "']").remove();
            }
        }
        if (picker.grid.checkbox.getCheckbox(false).length > 0) {
            picker.grid.checkbox.getHeaderRow().attr("checked", false);
        }
        picker.box.setCount();
    },
    //删除全部
    delAll: function (rows) {
        var arrlist = jQuery("#" + picker.setting.value).val().split(",");
        for (var j = 0; j < rows.length; j++) {
            for (var i = 0; i < arrlist.length; i++) {
                if (arrlist[i] == rows[j][picker.grid.fieldvalue]) {
                    picker.update(picker.setting.value, arrlist[i]);
                    picker.update("pickertext", rows[j][picker.grid.fieldtext]);
                    jQuery("#" + picker.setting.content + " option[value='" + rows[j][picker.grid.fieldvalue] + "']").remove();
                }
            }
        }
        picker.box.setCount();
    },
    //单选项移动
    singleMove: function () {
        var row = picker.grid.getSelectRow();
        jQuery("#" + picker.setting.content).html('');
        jQuery("#" + picker.setting.value).val(row.selectedvalue);
        jQuery("#" + picker.setting.text).val(row.selectedtext);
        jQuery("#" + picker.setting.content).append("<option value='" + row.selectedvalue + "'>" + row.selectedtext + "</option>");
        jQuery("#" + picker.setting.count).text("1");
    },
    //移动项
    move: function () {
        if (!picker.setting.ismultiple) {
            picker.box.singleMove();
        }
        else {
            var valobj = jQuery("#" + picker.setting.value);
            var txtobj = jQuery("#" + picker.setting.text);
            var row = picker.grid.checkbox.getSelections();
            var len = row.length;
            for (var i = 0; i < len; i++) {
                var txt = row[i][picker.grid.fieldtext];
                var val = row[i][picker.grid.fieldvalue];
                var arrlist = valobj.val().split(",");
                var sum = 0;
                //如果只选了一个对象
                if (arrlist.length == 1) {
                    valobj.val(val + "," + valobj.val());
                    txtobj.val(txt + "," + txtobj.val());
                    jQuery("#" + picker.setting.content).append("<option value='" + val + "'>" + txt + "</option>");
                }
                else {
                    //循环判断是否存在已选择的对象
                    for (var j = 0; j < arrlist.length; j++) {
                        if (arrlist[j] == val) {
                            sum++; //return;
                        }
                    }
                    //如果没有重复的选择对象
                    if (sum == 0) {
                        valobj.val(val + "," + valobj.val());
                        txtobj.val(txt + "," + txtobj.val());
                        jQuery("#" + picker.setting.content).append("<option value='" + val + "'>" + txt + "</option>");
                    }
                }
            }
            picker.grid.unSelectRow();
        }
    }
};

//picker.button继承
picker.box.button = {
    //清空
    clear: function () {
        jQuery("#" + picker.setting.value).val("");
        picker.grid.checkbox.clearSelections();
        jQuery("#" + picker.setting.content).html('');
        jQuery("#" + picker.setting.count).text("0");
        jQuery("#" + picker.setting.text).val("");
    },
    //删除
    del: function () {
        if (jQuery("#" + picker.setting.content + " > option:selected").length == 0) return;
        var boxobj = jQuery("#" + picker.setting.content);
        jQuery("#" + picker.setting.content + " > option:selected").each(function () {
            var arrlist = jQuery("#" + picker.setting.value).val().split(",");
            var o = jQuery(this);
            var index = o.index();
            for (var i = 0; i < arrlist.length; i++) {
                if (arrlist[i] == o.attr("value")) {
                    picker.update(picker.setting.value, arrlist[i]);
                    picker.update(picker.setting.text, o.attr("text"));
                    jQuery("#" + picker.setting.content + ">option[value='" + o.attr("value") + "']").remove();
                    //清除对应checkbox
                    picker.grid.checkbox.unCheckbox(arrlist[i]);
                    if (boxobj.children().length > index) {
                        boxobj.get(0).selectedIndex = index;
                    }
                    else {
                        boxobj.get(0).selectedIndex = index - 1;
                    }
                    if (picker.grid.checkbox.getCheckbox().length == 0) {
                        picker.grid.checkbox.getHeaderRow().attr("checked", false);
                    }
                    return;
                }
            }
        });
        picker.grid.unSelectRow();
    }
};


//设置值到pickerbox
function setValueToPickerBox(target) {
    target.jQuery("#temppickerid").val(picker.setting.pickerbox);
    target.jQuery("#temppickervalue").val(picker.box.getValue());
    if (jQuery.query.get('tagname') == "input") {
        target.jQuery("#temppickertext").val(picker.box.getText());
    }
    else
        target.jQuery("#temppickertext").val(picker.box.getContent());
    target.jQuery("#temppickercount").val(picker.box.getCount());
    target.jQuery("#temppickerbtn").attr("pickerboxid", picker.setting.pickerbox);
    target.jQuery("#temppickerbtn").click();
}

//for easyui datagrid
picker.grid = {
    datagrid: function (opts) {
        jQuery('#pickergrid').datagrid({
            url: opts.datagrid.url,
            width: opts.datagrid.width == undefined ? '700' : defaults.datagrid.width,
            height: 'auto',
            singleSelect: false,
            pagination: opts.datagrid.pagination == undefined ? false : defaults.datagrid.pagination,
            border: false,
            rownumbers: opts.datagrid.rownumbers == undefined ? false : defaults.datagrid.rownumbers,
            fitColumns: true,
            columns: opts.datagrid.columns,
            onLoadSuccess: function () {
                function bindRowsEvent() {
                    var panel = jQuery('#pickergrid').datagrid('getPanel');
                    var rows = panel.find('tr[datagrid-row-index]');
                    rows.unbind('click').bind('click', function () {
                        return false;
                    });
                    rows.find('div.datagrid-cell-check input[type=checkbox]').unbind().bind('click', function (e) {
                        var index = jQuery(this).parent().parent().parent().attr('datagrid-row-index');
                        if (jQuery(this).attr('checked')) {
                            jQuery('#pickergrid').datagrid('selectRow', index);
                            picker.box.move();
                        } else {
                            jQuery('#pickergrid').datagrid('unselectRow', index);
                        }
                        e.stopPropagation();
                    });
                    //header row
                    if (picker.setting.ismultiple == true) {
                        rows = panel.find('tr');
                        rows.find('div.datagrid-header-check input[type=checkbox]').unbind().bind('click', function (e) {
                            if (jQuery(this).attr('checked')) {
                                jQuery('#pickergrid').datagrid('selectAll');
                                picker.box.move();
                            } else {
                                jQuery('#pickergrid').datagrid('unselectAll');
                            }
                            e.stopPropagation();
                        });
                    }
                }
                setTimeout(function () {
                    bindRowsEvent();
                }, 10);
                picker.grid.showSelectedRow();
            },
            onUnselect: function (rowIndex, rowData) {
                picker.box.del(rowIndex, rowData);
            },
            onUnselectAll: function (rows) {
                picker.box.delAll(rows);
            }
        });
        var p = jQuery('#pickergrid').datagrid('getPager');
        jQuery(p).pagination({
            pageNumber: 1,
            pageList: [5, 10, 15], //可以设置每页记录条数的列表 
            beforePageText: '第',  //页数文本框前显示的汉字 
            afterPageText: '页  共 {pages} 页',
            displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录',
            onSelectPage: function (pageNumber, pageSize) {
                jQuery('#pickergrid').datagrid('reload', jQuery.extend({
                    'currentPage': pageNumber,
                    'pageSize': pageSize
                },
                defaults.datagrid.queryParams)
                );
                picker.grid.showSelectedRow();
            }
        });
    },
    checkbox: {
        //获取所有checkbox对象
        getCheckbox: function (type) {
            var panel = jQuery('#pickergrid').datagrid('getPanel');
            var rows = panel.find('tr[datagrid-row-index]');
            if (type)
                return rows.find('div.datagrid-cell-check input[type=checkbox]:checked');
            else {
                return rows.find('div.datagrid-cell-check input[type=checkbox]:not(input:checked)');
            }
        },
        //获取头行
        getHeaderRow: function () {
            var panel = jQuery('#pickergrid').datagrid('getPanel');
            var rows = panel.find('tr');
            return rows.find('div.datagrid-header-check input[type=checkbox]');
        },
        //清空所有选项
        clearSelections: function () {
            picker.grid.checkbox.getHeaderRow().attr("checked", false);
            jQuery('#pickergrid').datagrid('clearSelections');
        },
        //获取所有已选择的行
        getSelections: function () {
            return jQuery('#pickergrid').datagrid('getSelections');
        },
        //取消选择
        unCheckbox: function (selectedvalue) {
            var rows = jQuery('#pickergrid').datagrid('getRows');
            for (var i = 0; i < rows.length; i++) {
                if (rows[i][picker.grid.fieldvalue] == selectedvalue) {
                    jQuery('#pickergrid').datagrid('unselectRow', i);
                }
            }
        }
    },
    getRows: function () {
        return jQuery('#pickergrid').datagrid('getRows');
    },
    getSelectRow: function () {
        var row = jQuery('#pickergrid').datagrid('getSelected');
        var text = '', value = '';
        if (typeof (row[picker.grid.fieldtext] == "Object")) {
            text = row[picker.grid.fieldtext];
        }
        if (typeof (row[picker.grid.fieldvalue] == "Object")) {
            value = row[picker.grid.fieldvalue];
        }
        var r = {
            selectedtext: text,
            selectedvalue: value
        };
        return r;
    },
    fieldtext: "",
    fieldvalue: "",
    //取消/选择行
    unSelectRow: function () {
        var panel = jQuery('#pickergrid').datagrid('getPanel');
        var rows = panel.find('tr[datagrid-row-index]');
        var len = rows.find('div.datagrid-cell-check input[type=checkbox]:checked').length;
        var totallen = rows.find('div.datagrid-cell-check input[type=checkbox]').length;
        if (len == totallen) {
            picker.grid.checkbox.getHeaderRow().attr("checked", true);
        } else {
            picker.grid.checkbox.getHeaderRow().attr("checked", false);
        }
        picker.box.setCount();
    },
    //显示已选行
    showSelectedRow: function () {
        var rows = jQuery('#pickergrid').datagrid('getRows');
        for (var i = 0; i < rows.length; i++) {
            var arrlist = jQuery("#" + picker.setting.value).val().split(",");
            for (var j = 0; j < arrlist.length - 1; j++) {
                if (rows[i][picker.grid.fieldvalue] == arrlist[j]) {
                    jQuery('#pickergrid').datagrid('selectRow', i);
                }
            }
        }
        if (picker.grid.checkbox.getCheckbox(true).length == parseInt(rows.length)) {
            picker.grid.checkbox.getHeaderRow().attr("checked", true);
        }
        else {
            picker.grid.checkbox.getHeaderRow().attr("checked", false);
        }
        picker.box.setCount();
    }
};